<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>预约回收 - 废物回收管理系统</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        #addressMap {
            width: 100%;
            height: 400px;
            margin: 15px 0;
            position: relative;
            overflow: hidden;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #f8f9fa;
            z-index: 1;
        }
        .address-search {
            margin-bottom: 10px;
            position: relative;
            z-index: 2;
        }
        .card-body {
            padding: 1rem;
            position: relative;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/resident">
                <i class="fas fa-recycle me-2"></i>废物回收管理系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" href="/resident">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/orders/create">预约回收</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/resident/orders">我的订单</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/stations/map">回收站地图</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <h2 class="mb-4">预约回收</h2>
        <form id="orderForm" onsubmit="return submitOrder(event)">
            <div class="card mb-4">
                <div class="card-body">
                    <h5 class="card-title">选择回收地址</h5>
                    
                    <!-- 地址搜索框 -->
                    <div class="input-group mb-3">
                        <input type="text" class="form-control" id="address-search" placeholder="搜索地址">
                        <button class="btn btn-outline-primary" type="button" onclick="searchAddress()">
                            <i class="fas fa-search"></i> 搜索
                        </button>
                    </div>
                    
                    <!-- 地图容器 -->
                    <div id="addressMap"></div>
                    
                    <!-- 详细地址输入框 -->
                    <div class="mt-3">
                        <label class="form-label">详细地址</label>
                        <input type="text" class="form-control" id="detailed-address" name="detailedAddress" readonly>
                        <div class="form-text">点击地图或搜索选择位置后会自动填充</div>
                    </div>
                    
                    <input type="hidden" id="latitude" name="latitude">
                    <input type="hidden" id="longitude" name="longitude">
                    <input type="hidden" id="address" name="address">
                    
                    <div class="mb-3">
                        <label class="form-label">联系人</label>
                        <input type="text" class="form-control" name="contactName" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">联系电话</label>
                        <input type="tel" class="form-control" name="contactPhone" required>
                    </div>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-body">
                    <h5 class="card-title">回收信息</h5>
                    
                    <div class="mb-3">
                        <label class="form-label">物品类型</label>
                        <select class="form-select" name="itemType" required>
                            <option value="">请选择物品类型</option>
                            <option value="PAPER">废纸</option>
                            <option value="PLASTIC">塑料</option>
                            <option value="METAL">金属</option>
                            <option value="APPLIANCE">电器</option>
                            <option value="OTHER">其他</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">预估重量（kg）</label>
                        <input type="number" class="form-control" name="estimatedWeight" required min="0" step="0.1">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">预约时间</label>
                        <input type="datetime-local" class="form-control" name="appointmentTime" required>
                    </div>
                </div>
            </div>
            
            <button type="submit" class="btn btn-primary">提交预约</button>
        </form>
    </div>

    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">最近订单</h5>
            <a href="/resident/orders" class="btn btn-primary btn-sm">查看全部</a>
        </div>
        <div class="card-body">
            <div id="recentOrders">
                <!-- 订单列表将通过JavaScript动态加载 -->
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <!-- 百度地图API -->
    <script type="text/javascript">
        function loadScript() {
            console.log('开始加载百度地图API...');
            var script = document.createElement("script");
            script.src = "https://api.map.baidu.com/api?v=3.0&ak=mNFuffn83uuKvzWesj3uqfVho6CVP9LI&callback=initMap";
            script.onerror = function() {
                console.error('百度地图API加载失败');
            };
            document.head.appendChild(script);
        }

        // 页面加载完成后加载地图API
        if (document.readyState === 'complete') {
            loadScript();
        } else {
            window.addEventListener('load', loadScript);
        }
    </script>
    <script th:inline="javascript">
        let map = null;
        
        // 初始化地图
        function initMap() {
            try {
                console.log('开始初始化地图...');
                
                // 确保地图容器存在
                const container = document.getElementById('addressMap');
                if (!container) {
                    throw new Error('地图容器不存在');
                }
                
                // 创建地图实例
                map = new BMap.Map('addressMap', {
                    enableMapClick: true,
                    minZoom: 4,
                    maxZoom: 19
                });
                
                // 创建点坐标
                const point = new BMap.Point(116.404, 39.915); // 默认北京
                map.centerAndZoom(point, 15);
                
                // 开启鼠标滚轮缩放
                map.enableScrollWheelZoom();
                // 开启拖拽
                map.enableDragging();
                // 开启双击放大
                map.enableDoubleClickZoom();
                
                // 添加地图控件
                map.addControl(new BMap.NavigationControl());     // 添加平移缩放控件
                map.addControl(new BMap.ScaleControl());         // 添加比例尺控件
                map.addControl(new BMap.OverviewMapControl());   // 添加缩略地图控件
                map.addControl(new BMap.MapTypeControl());       // 添加地图类型控件
                
                // 尝试获取用户位置
                const geolocation = new BMap.Geolocation();
                geolocation.getCurrentPosition(function(r) {
                    if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                        const mk = new BMap.Marker(r.point);
                        map.addOverlay(mk);
                        map.panTo(r.point);
                        map.setZoom(15);
                        
                        // 解析地址
                        const geocoder = new BMap.Geocoder();
                        geocoder.getLocation(r.point, function(rs) {
                            const addComp = rs.addressComponents;
                            const address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                            document.getElementById('detailed-address').value = address;
                            document.getElementById('address').value = address;
                            document.getElementById('latitude').value = r.point.lat;
                            document.getElementById('longitude').value = r.point.lng;
                        });
                    }
                });
                
                // 点击地图事件
                map.addEventListener('click', function(e) {
                    map.clearOverlays();
                    const marker = new BMap.Marker(e.point);
                    map.addOverlay(marker);
                    
                    const geocoder = new BMap.Geocoder();
                    geocoder.getLocation(e.point, function(rs) {
                        const addComp = rs.addressComponents;
                        const address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                        document.getElementById('detailed-address').value = address;
                        document.getElementById('address').value = address;
                        document.getElementById('latitude').value = e.point.lat;
                        document.getElementById('longitude').value = e.point.lng;
                    });
                });
                
                // 添加搜索功能
                const ac = new BMap.Autocomplete({
                    "input": "address-search",
                    "location": map
                });
                
                ac.addEventListener("onconfirm", function(e) {
                    const _value = e.item.value;
                    const address = _value.province + _value.city + _value.district + _value.street + _value.business;
                    
                    const local = new BMap.LocalSearch(map, {
                        onSearchComplete: function() {
                            const pp = local.getResults().getPoi(0).point;
                            map.centerAndZoom(pp, 15);
                            map.clearOverlays();
                            const marker = new BMap.Marker(pp);
                            map.addOverlay(marker);
                            document.getElementById('detailed-address').value = address;
                            document.getElementById('address').value = address;
                            document.getElementById('latitude').value = pp.lat;
                            document.getElementById('longitude').value = pp.lng;
                        }
                    });
                    local.search(address);
                });
                
                console.log('地图初始化完成');
            } catch (error) {
                console.error('地图初始化失败:', error);
            }
        }

        // 地址搜索按钮点击事件
        function searchAddress() {
            const address = document.getElementById('address-search').value;
            if (address) {
                setPlace(address);
            }
        }

        // 提交订单
        function submitOrder(event) {
            event.preventDefault();
            
            const formData = new FormData(event.target);
            const order = {
                address: formData.get('address'),
                latitude: parseFloat(formData.get('latitude')),
                longitude: parseFloat(formData.get('longitude')),
                contactName: formData.get('contactName'),
                contactPhone: formData.get('contactPhone'),
                itemType: formData.get('itemType'),
                estimatedWeight: parseFloat(formData.get('estimatedWeight')),
                appointmentTime: formData.get('appointmentTime')
            };
            
            // 添加表单验证
            if (!order.address) {
                alert('请选择回收地址');
                return false;
            }
            
            if (!order.latitude || !order.longitude) {
                alert('地址坐标获取失败,请重新选择地址');
                return false;
            }
            
            fetch('/api/orders/create', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(order)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('订单创建失败');
                }
                return response.json();
            })
            .then(data => {
                alert('订单创建成功！');
                window.location.href = '/resident/orders';
            })
            .catch(error => {
                console.error('创建订单失败:', error);
                alert('创建订单失败: ' + error.message);
            });
            
            return false;
        }

        // 加载最近订单
        function loadRecentOrders() {
            fetch('/api/orders?page=0&size=5')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取订单失败');
                    }
                    return response.json();
                })
                .then(data => {
                    const ordersDiv = document.getElementById('recentOrders');
                    if (data.content && data.content.length > 0) {
                        const ordersList = data.content.map(order => `
                            <div class="card mb-2">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <h6 class="card-title mb-1">订单号: ${order.id}</h6>
                                            <p class="card-text mb-1">
                                                <small class="text-muted">
                                                    预约时间: ${new Date(order.appointmentTime).toLocaleString()}
                                                </small>
                                            </p>
                                            <p class="card-text mb-1">地址: ${order.address}</p>
                                            <p class="card-text mb-0">
                                                <span class="badge bg-${getStatusBadgeClass(order.status)}">
                                                    ${getStatusText(order.status)}
                                                </span>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `).join('');
                        ordersDiv.innerHTML = ordersList;
                    } else {
                        ordersDiv.innerHTML = '<div class="text-center py-4"><i class="fas fa-inbox fa-3x text-muted"></i><p class="mt-2 text-muted">暂无订单记录</p></div>';
                    }
                })
                .catch(error => {
                    console.error('加载订单失败:', error);
                    document.getElementById('recentOrders').innerHTML = 
                        '<div class="alert alert-danger">加载订单失败，请稍后重试</div>';
                });
        }

        // 获取状态对应的样式类
        function getStatusBadgeClass(status) {
            switch (status) {
                case 'PENDING': return 'warning';
                case 'ACCEPTED': return 'info';
                case 'IN_PROGRESS': return 'primary';
                case 'COMPLETED': return 'success';
                case 'CANCELLED': return 'danger';
                default: return 'secondary';
            }
        }

        // 获取状态的中文描述
        function getStatusText(status) {
            switch (status) {
                case 'PENDING': return '待处理';
                case 'ACCEPTED': return '已接单';
                case 'IN_PROGRESS': return '处理中';
                case 'COMPLETED': return '已完成';
                case 'CANCELLED': return '已取消';
                default: return '未知状态';
            }
        }

        // 页面加载完成后加载订单列表
        document.addEventListener('DOMContentLoaded', loadRecentOrders);
    </script>
</body>
</html> 